package com.test.demo.utils;

import android.content.Context;
import android.os.Build;

import com.afollestad.date.BuildConfig;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * @author
 * @version 1.0.0
 * @projectName
 * @description:
 * @date : 2024/2/20 10:56
 */
public class MyExceptionHandler implements Thread.UncaughtExceptionHandler {

    Context context;

    public MyExceptionHandler(Context context) {
        this.context = context;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        // 处理未捕获异常
        saveCrashInfoToFile(ex);

        // 这里可以根据需要执行其他操作，比如重启应用
        // restartApp();

        // 终止应用
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);
    }

    private void saveCrashInfoToFile(Throwable ex) {

        try {
            // 创建崩溃日志文件
            File logFile = new File(context.getExternalFilesDir(null), "crash_log.txt");
            PrintWriter writer = new PrintWriter(new FileWriter(logFile, true));

            // 写入异常信息
            writer.println("Crash Time: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date()));
            writer.println("Device: " + Build.MODEL + " (" + Build.DEVICE + ")");
            writer.println("Android Version: " + Build.VERSION.RELEASE);
            writer.println("App Version: " + BuildConfig.VERSION_NAME);
            writer.println();
            ex.printStackTrace(writer);

            // 关闭写入流
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
